/*
 * Copyright 2012 JooKar BV (info@jookar.nl)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.jookar.android.simpleclock;

import java.util.Calendar;
import java.util.Date;

import nl.jookar.android.simpleclock.alarm.AlarmReceiver;
import nl.jookar.android.simpleclock.prefs.AlarmSettingsActivity;
import nl.jookar.android.simpleclock.views.AnimatedDigitView;
import nl.jookar.android.simpleclock.views.ClockType;
import nl.jookar.android.simpleclock.views.IClockView;
import nl.jookar.android.utils.gesture.SwipeDetector.OnSwipeAdapter;
import nl.jookar.android.utils.misc.SystemUtils;
import nl.jookar.android.utils.ui.Toast;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

/**
 * @author Joost A. Bloemsma
 *
 */
public class SimpleClockActivity extends Activity {
	private static final String DEBUG_TAG = SimpleClockActivity.class.getName();
	
	//private AnimatedDigitView clock;
	private IClockView clock;
	private static final int TICK_WHAT = 2;
	private int refreshInterval = 1000;
	private boolean isRunning = false;
	private RelativeLayout root;
	private Button btn;
	private static ClockHandler handler;
	private int originalBrightness = 255;
	private boolean isDimmed = false;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Make sure there is nothing else on the screen but the clock
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        setContentView(R.layout.main);
        root = (RelativeLayout)findViewById(R.id.mainRoot);
        
        RelativeLayout.LayoutParams layout = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layout.addRule(RelativeLayout.CENTER_IN_PARENT);

        try {
			clock = AnimatedDigitView.class.newInstance();
			root.addView((View)clock,layout);
	        clock.set24H(true);
	        if (handler != null) handler.removeMessages(TICK_WHAT);
	        handler = null;
	        start();
		} catch (InstantiationException e) {
			Log.e(DEBUG_TAG, "Could not create clockview", e);
		} catch (IllegalAccessException e) {
			Log.e(DEBUG_TAG, "Could not create clockview", e);
		}
        
        /* Swipe detection  */
        Log.d(DEBUG_TAG, "Installing swipe adapter");
        
        @SuppressWarnings("unused")
		OnSwipeAdapter onSwipeAdapter = new OnSwipeAdapter(root) {
        	/**
    		 * {@inheritDoc}
    		 */
    		@Override
    		public boolean onUpSwipe(float distance, float velocity) {
    			dimOff();
    			return true;
    		}

    		/**
    		 * {@inheritDoc}
    		 */
    		@Override
    		public boolean onDownSwipe(float distance, float velocity) {
    			dimOn();
    			return true;
    		}
        };
        
        /* TEST CODE FROM HERE */
        btn = (Button)findViewById(R.id.btnTest);
        btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				/*
				Set the alarm:
				
				// get a Calendar object with current time
				 Calendar cal = Calendar.getInstance();
				 // add 5 minutes to the calendar object
				 cal.add(Calendar.MINUTE, 5);
				 Intent intent = new Intent(ctx, AlarmReceiver.class);
				 intent.putExtra("alarm_message", "O'Doyle Rules!");
				 // In reality, you would want to have a static variable for the request code instead of 192837
				 PendingIntent sender = PendingIntent.getBroadcast(this, 192837, intent, PendingIntent.FLAG_UPDATE_CURRENT);
				 
				 // Get the AlarmManager service
				 AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
				 am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
				
				 */
				Context ctx = getApplicationContext();
				Calendar cal = Calendar.getInstance();
				cal.add(Calendar.SECOND, 5);
				Intent intent = new Intent(ctx, AlarmReceiver.class);
				intent.putExtra(AlarmReceiver.PARM_MSG, "Yes! did it!");
				PendingIntent sender = PendingIntent.getBroadcast(ctx, AlarmReceiver.REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
				AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
				am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
			}
		});

    }
    
	/**
	* Inflate Menu from XML and add optional clock specific items
	*/
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    super.onCreateOptionsMenu(menu);
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.mainmenu, menu);
	    MenuItem temp = menu.findItem(R.id.mnuSelectType);
	    SubMenu sub = temp.getSubMenu();
	    return clock.addClockMenu(sub);
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) { 
		int id = item.getItemId();
		switch (id) {
			case R.id.mnuAlarm:
				startActivity(new Intent(getApplicationContext(), AlarmSettingsActivity.class));
				return true;
		}
		
		// Try the ClockView 
		if (clock.onOptionsItemSelected(item)) return true;
		
	    return false;
	}
    
    /**
     * The 'tick' of the clock. Get's triggered every interval.
     */
    public void tick() {
    	clock.setTime(new Date());
    }
    
    private void start() {
    	if (handler == null) {
    		handler = new ClockHandler(this);
    	}
    	isRunning = true;
    	handler.sendMessageAtTime(Message.obtain(handler, TICK_WHAT), 1);
    }
    
    private void dimOn() {
    	if (isDimmed) return;
    	Toast.showShort(getApplicationContext(), "Dimming screen");
    	
    	originalBrightness = SystemUtils.getSettingInt(this, Settings.System.SCREEN_BRIGHTNESS, 255);
    	Log.d(DEBUG_TAG, "Setting brightness from " + Integer.toString(originalBrightness) + " to 20");
    	SystemUtils.setSetting(this, Settings.System.SCREEN_BRIGHTNESS, 20);
    	
    	isDimmed = true;
    }
    
    private void dimOff() {
    	if (!isDimmed) return; 
    	Toast.showShort(getApplicationContext(), "Undimming screen");
    	
    	Log.d(DEBUG_TAG, "Setting brightness from 20 to " + Integer.toString(originalBrightness));
    	SystemUtils.setSetting(this, Settings.System.SCREEN_BRIGHTNESS, originalBrightness);
    	
    	isDimmed = false;
    }
    
    /**
     * Handles the interval message  
     * @author Joost A. Bloemsma
     *
     */
    private static class ClockHandler extends Handler {
    	private static final String DEBUG_TAG_HANDLER = ClockHandler.class.getName();
    	private SimpleClockActivity _act;
    	
    	private ClockHandler(SimpleClockActivity act) {
    		_act = act;
    	}
    	
    	/**
    	 * {@inheritDoc}
    	 */
    	@Override
		public void handleMessage(Message m) {
    		if (_act == null) {
    			Log.w(DEBUG_TAG_HANDLER,"Activity not valid while handling message");
    			return;
    		}
			if (!_act.isRunning) return;
			_act.tick();
			sendMessageDelayed(Message.obtain(this, TICK_WHAT), _act.refreshInterval);
		}
    }


}

